package com.vic.framework.utils;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 属性文件工具类
 * @author VIC
 *
 */
public final class PropsUtils {

	private static final Logger logger = LoggerFactory.getLogger(PropsUtils.class);

	/**
	 *加载属性文件
	 */
	
	public static Properties loadProps(String fiileName) {
		Properties properties = null;
		InputStream is = null;
		try{
			is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fiileName);
			if(is == null) {
				throw new FileNotFoundException(fiileName + " is not found");
			}
			properties = new Properties();
			properties.load(is);
		}catch(IOException e){
			logger.error("load properties file failure", e);
		}finally {
			if(is != null) {
				try {
					is.close();
				} catch (IOException e) {
					logger.error("close  InputStream  failure", e);
				}
			}
		}
		return properties;
	}
	
	
	public static String getString(Properties properties, String key){
		return getString(properties, key, "");
	}


	public static String getString(Properties properties, String key, String defaultValue) {
		String value = defaultValue;
		if(properties.containsKey(key)) {
			value = properties.getProperty(key);
		}
		return value;
	}
	
	public static int getInt(Properties properties, String key) {
		return getInt(properties, key, 0);
	}


	public static int getInt(Properties properties, String key, int defaultValue) {
		int value = defaultValue;
		if(properties.containsKey(key)) {
			try{
				
				value = Integer.parseInt(properties.getProperty(key));
			}catch(NumberFormatException e) {
			}
		}
		return value;
	}
	
	
	public static boolean getBoolean(Properties properties, String key) {
		return getBoolean(properties, key, false);
	}


	private static boolean getBoolean(Properties properties, String key, boolean defaultValue) {
		boolean value = defaultValue;
		if(properties.containsKey(key)) {
			try{
				
				value = Boolean.parseBoolean(properties.getProperty(key));
			}catch(NumberFormatException e) {
			}
		}
		return value;
	}
	
	
}
